class NilClass
  def innerHTML; nil; end
end

require 'hpricot'

module TalkShoe
  class Episode
    
    attr_reader :start_time, :id, :name, :host_name, :live, :past, :phone, :talkcast
    
    def initialize(options)
      if options.is_a?(String)
        initialize_from_xml(options)
      elsif options.is_a?(Hash)
        initialize_from_hash(options) 
      else
        raise ArgumentError.new("Cannot create TalkShoe::Episode from #{options}")
      end
    end
    
    def initialize_from_xml(xml)
      begin
        doc = Hpricot.XML(xml)
      
        @start_time = doc.at('episodeDate').innerHTML
        @id = doc.at('episodeId').innerHTML
        @name = doc.at('episodeName').innerHTML
        @host_name = doc.at('hostName').innerHTML
        @live = (doc.at('live').innerHTML == 'true')
        @past = (doc.at('past').innerHTML == 'true')
        @phone = doc.at('phoneNumber').innerHTML
        @talkcast = TalkCast.new(
          :id => doc.at('talkcastId').innerHTML,
          :name => doc.at('talkcastName').innerHTML,
          :rss_url => doc.at('rssURL').innerHTML,
          :stream_url => doc.at('streamUrl').innerHTML
        )
      rescue Exception => e
        raise "Error parsing XML from TalkShoe: #{e}"
      end
    end
    
    def initialize_from_hash(hash)    
      @start_time = hash[:start_time]
      @id = hash[:id]
      @name = hash[:name]
      @host_name = hash[:host_name]
      @live = hash[:live]
      @past = hash[:past]
      @phone = hash[:phone]
      @talkcast = TalkCast.new(hash[:talkcast])
    end
    
    def start_time=(time)
      if time.kind_of?(Time)
        @start_time = time
      elsif time.kind_of?(String)
        @start_time = Time.parse(time)
      else
        raise ArgumentError.new("Cannot create a Time object from #{time}")
      end
    end
    
    def live?; live; end
    def past?; past; end
    
    private :initialize_from_xml, :initialize_from_hash
    
  end
end